import PyPDF2
from PIL import Image
from docx import Document
from openai import OpenAI

# app = Flask(__name__)

# 设置你的DeepSeek API密钥
DEEPSEEK_API_KEY = 'sk-254854d6a62944dd950b5ba938a5c024'
client = OpenAI(api_key=DEEPSEEK_API_KEY, base_url="https://api.deepseek.com")

# 允许的文件扩展名
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'docx', 'jpg', 'jpeg', 'png'}


def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


def read_text_file(file_stream):
    return file_stream.read().decode('utf-8')


def read_docx_file(file_stream):
    doc = Document(file_stream)
    full_text = []
    for para in doc.paragraphs:
        full_text.append(para.text)
    return '\n'.join(full_text)


def read_pdf_file(file_stream):
    pdf_reader = PyPDF2.PdfReader(file_stream)
    full_text = []
    for page_num in range(len(pdf_reader.pages)):
        page = pdf_reader.pages[page_num]
        full_text.append(page.extract_text())
    return '\n'.join(full_text)


def read_image_file_local(file_path):
    image = Image.open(file_path)
    return image


def read_image_file(file_stream):
    image = Image.open(file_stream)
    return image


def ask_question(content, question):
    response = client.chat.completions.create(
        model="deepseek-chat",
        messages=[
            {"role": "system", "content": "You are a helpful assistant"},
            {"role": "user", "content": f"{content}\n\nQuestion: {question}"},
        ],
        stream=False
    )
    return response.choices[0].message.content.strip()


def ask_keyword(key):
    keyword = {
        "ID": "请给出正确的身份证信息,包含:姓名、性别、民族、出生、身份证号、住址，身份证号必须是完整的18位数字,格式为 {type:ID,name:xxx,sex:xxx,nation:xxx ,birth:xxx,idNo:xxxxxxxxxxxxxxxxx ,address:xxx},只返回json格式数据！",
        "Bank": "请给出正确的银行卡号和银行名称信息,银行卡号必须是完整的19位数字或者16位数字,""由前面6位数字加后面13位数字构成的19位数字或者由连续的4位构成的16位数字并且连续的4位数字不会重复，""银行名称必须是中文，格式为 {type:bank,cardNo:xxxxxx xxxxxxxxxxxxx or xxxx xxxx xxxx xxxx，cardName:招商银行} carNO 即银行卡号 必须是19位或者16位数字,只返回json格式数据！",
        "License": "请给出正确的营业执照信息,包含:营业执照注册号即（统一社会信用代码）、公司名称即（名称）、公司类型、法定代表人、经营范围、注册资本、成立日期、营业期限、住所即（公司地址），营业执照注册号必须是完整的18位数字,""格式为 {type:license,licenseNo:xxxxxxxxxxxxxxxxx,companyName:xxx,companyType:xxxx,corporation:xxx,scope:xxx,registeredCapital:xxx,establishmentDate:xxx,businessPeriod:xxx,companyAddress:xxx},只返回json格式数据！"
    }
    return keyword.get(key, "Unknown")


def chat_allowed_file(filename, file_stream):
    if allowed_file(filename):
        file_extension = filename.split('.')[-1].lower()

        if file_extension == 'txt':
            file_content = read_text_file(file_stream)
        elif file_extension == 'docx':
            file_content = read_docx_file(file_stream)
        else:
            file_content = read_pdf_file(file_stream)
        return file_content, 200
    else:
        return {"error": "File type not allowed"}, 400
